 
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // screenHeight: 0,
    formatInfo:'',
    id:'',
    types: ["上课签到", ],
    types1: ["倒计时签到","手动控制签到" ],
    typeslist: [],
    typeIndex: "0",
    typeIndex1: "0",
    titleHistory: [],
    nameHistory: [],
    captionHistory: [],
    showTitleHistory: false,
    showNameHistory: false,
    showCaptionHistory: false,
    hasTwo: true,
    currentIndex: 0,
    point: false,

    activities: ["签到", "签退"],
    activityIndex: "0",
    formatName:'',
    title: '',
    desc: '',
    timeslist:[1,2,3,4,5],
    timesIndex:'0',
    timelist: [1, 2, 3, 4, 5, 10, 15, 20, 25, 30],
    timeIndex: "0",
    // time: '00:00',
    rangement:0,
    classList: {},

    lists: [],
    listIndex: "0",
    times:1,
    signlist:'',

    pubdata: {},

    userinfo: {},

    listflag: true,

    pointflag: [
      
    ],
    pointflag2:false,
    choosen: {
      latitude: 0,
      longitude: 0
    },
    flag1: false,

    scopelist: [300, 400, 500, 800, 1000, 1500, 2000, 2500, 3000],
    scopeIndex: 2,

    navConfig: {
      title: '确认框',
      type: 1,
      config: {
        show: true,
        type: 'confirm',
        showTitle: true,
        title: '标题',
        content: '这个是确认框',
        confirmText: '确定',
        confirmColor: '#3683d6',
        cancelText: '取消',
        cancelColor: '#999'
      }
    },
    firstTip: true,
    templateId:null,
    flag:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    wx.User.checkFlag()
    this.setData({
      flag: wx.getStorageSync('checkFlag').data,
    })
    console.log(this.data.pointflag);
    this.data.userinfo = wx.User.userinfo
    this.getList()
    this.data.id=options.id
      console.log('id'+this.data.id);
      await wx.User.getFormatInfo({
        data:{
          templateId:this.data.id
        }
      })
      this.data.formatInfo=wx.getStorageSync('formatInfo')
      console.log('format');
      console.log(this.data.formatInfo);
      var fi=this.data.formatInfo
      this.data.templateId=fi.id
      this.data.title=fi.title
      this.data.desc=fi.caption
      this.data.typeIndex=String(fi.actType-1)
      this.data.typeIndex1=String(fi.signStopType)
      if(fi.cid != ""){
        this.data.pointflag2=true
        console.log(this.data.classList)
        for(var i=0;i<this.data.classList.length;i++){
          console.log("haha")
          if(this.data.classList[i].id==fi.cid){
            this.data.listIndex = i
          }
        }
      }
      var signlist=[]
      
      console.log(this.toInt(fi.linkType));
      for(var i in this.toInt(fi.linkType)){
        signlist.push({
          linkType:this.toInt(fi.linkType)[i],
          duration:this.toInt(fi.duration)[i],
          times:this.toInt(fi.times)[i],
          whetherLocation:this.toInt(fi.whetherLocation)[i],
          range:fi.rangement
        })
        if(this.toInt(fi.whetherLocation)[i]==1){
          this.data.pointflag[i]=true
        }else{
          this.data.pointflag[i]=false
        }
      }
  
      console.log('list');
      console.log(signlist);
      this.data.signlist=signlist
      this.setData({
        title:this.data.title,
        desc:this.data.desc,
        typeIndex:this.data.typeIndex,
        typeIndex1:this.data.typeIndex1,
        signlist:this.data.signlist,
        pointflag:this.data.pointflag,
        pointflag2:this.data.pointflag2,
        listIndex:this.data.listIndex
      })
      console.log(this.data.pointflag);
      this.data.userinfo = wx.User.userinfo
      console.log("as")
      

      if (this.data.signlist.length == 2) {
        this.setData({
          hasTwo: true
        })
      }else{
        this.setData({
          hasTwo: false
        })
      }
   
  },


  onShow: function () {
    this.data.userinfo = wx.User.userinfo
    this.getList()
    this.getTypeList()

  },

  toInt(option){
    var dataStrArr=option.split(",");//分割成字符串数组  
    var dataIntArr=[];//保存转换后的整型字符串  
  
    //方法一  
    dataStrArr.forEach(function(data,index,arr){  
        dataIntArr.push(+data);  
    });  
    return dataIntArr
  },

  nameInput(e) {
      this.data.formatName = e.detail.value
      console.log(this.data.formatName);
  },

  titleInput(e) {
    if (e.type == "focus") {
      this.setData({
        showTitleHistory: true
      })
    }
    if (e.type == "blur") {
      this.setData({
        showTitleHistory: false
      })
      this.data.title = e.detail.value
      console.log(this.data.title);
      setTimeout(() => {
        var list = this.data.titleHistory
        if (e.detail.value != "") {
          for (var i = 0; i < list.length; i++) {
            if (list[i] == this.data.title) {
              list.splice(i, 1)
              list.splice(0, 0, this.data.title)
              this.setData({
                titleHistory: list
              })
              wx.setStorageSync('titleHistory', list)
              return;
            }
          }
          if (list.length == 5) {
            list.splice(4, 1)
          }
          list.splice(0, 0, this.data.title)
        }
        this.setData({
          showCaptionHistory: false,
          titleHistory: list
        })
        wx.setStorageSync('titleHistory', list)
      }, 500)
    }
  },

  captionInput(e) {
    if (e.type == "focus") {
      this.setData({
        showCaptionHistory: true
      })
    }
    if (e.type == "blur") {
      this.setData({
        showCaptionHistory: false
      })
      this.data.desc = e.detail.value
      setTimeout(() => {
        var list = this.data.captionHistory
        if (e.detail.value != "") {
          for (var i = 0; i < list.length; i++) {
            if (list[i] == this.data.desc) {
              list.splice(i, 1)
              list.splice(0, 0, this.data.desc)
              this.setData({
                captionHistory: list
              })
              wx.setStorageSync('captionHistory', list)
              return;
            }
          }
          if (list.length == 5) {
            list.splice(4, 1)
          }
          list.splice(0, 0, this.data.desc)
        }
        this.setData({
          showCaptionHistory: false,
          captionHistory: list
        })
        wx.setStorageSync('captionHistory', list)
      }, 500)
    }
  },

  titleTap(e) {
    var index = e.currentTarget.dataset.index
    this.data.title = this.data.titleHistory[index]
    this.setData({
      title: this.data.title
    })
  },

  captionTap(e) {
    var index = e.currentTarget.dataset.index
    this.data.desc = this.data.captionHistory[index]
    this.setData({
      desc: this.data.desc
    })
  },

    // 导入名单
    import_name(e){ 
      console.log("haha")
      this.getList()
      var tmp = this.data.pointflag2
      tmp = ! tmp
      if(tmp){
        this.setData({
          pointflag2: tmp,
          currentIndex: e.currentTarget.dataset.index,
          modalName: e.currentTarget.dataset.target
        })
      }else{
        this.setData({
          pointflag2: tmp,
          currentIndex: e.currentTarget.dataset.index,
          listIndex:"0"
        })
      }
    },

  // 定位单选框点击
  clisk(e) {
    var tmp = this.data.pointflag
    tmp[e.currentTarget.dataset.index] = !tmp[e.currentTarget.dataset.index]
    if (tmp[e.currentTarget.dataset.index]) {
      this.setData({
        pointflag: tmp,
        currentIndex: e.currentTarget.dataset.index,
        modalName: e.currentTarget.dataset.target
      })
    } else {
      var link = this.data.signlist;
      link[e.currentTarget.dataset.index].location_x = 0;
      link[e.currentTarget.dataset.index].location_y = 0;
      link[e.currentTarget.dataset.index].range = 0;
      link[e.currentTarget.dataset.index].whetherLocation = 0;
      this.setData({
        pointflag: tmp,
        currentIndex: e.currentTarget.dataset.index,
        signlist: link
      })
    }
  },

  locationDetermine() {
    var index = this.data.currentIndex
    var location_x = 0
    var location_y = 0
    var range = 0
    if (this.data.pointflag[index]) {
      location_x = this.data.choosen.latitude
      location_y = this.data.choosen.longitude
      range = this.data.scopelist[this.data.scopeIndex]
      if (this.data.choosen.latitude == 0 && this.data.choosen.longitude == 0) {
        wx.showToast({
          title: '请选择位置！',
          icon: 'none'
        })
      } else {
        this.data.signlist[index].location_x = location_x;
        this.data.signlist[index].location_y = location_y;
        this.data.signlist[index].range = range;
        this.data.signlist[index].whetherLocation = 1;
        this.setData({
          signlist: this.data.signlist
        })
        this.hideModal()
      }
    } else {
      this.data.signlist[index].location_x = location_x;
      this.data.signlist[index].location_y = location_y;
      this.data.signlist[index].range = range;
      this.data.signlist[index].whetherLocation = 0;
      this.setData({
        signlist: this.data.signlist
      })
      this.hideModal()
    }
  },

  timesAdd(e){
    var index = e.currentTarget.dataset.index
    if (this.data.signlist[index].times == 5){
      return;
    }
    else{
      this.data.signlist[index].times++
    }
    this.setData({
      signlist: this.data.signlist
    })
  },
  timesMin(e){
    var index = e.currentTarget.dataset.index
    if (this.data.signlist[index].times == 1){
      return;
    }
    else{
      this.data.signlist[index].times--
    }
    this.setData({
      signlist: this.data.signlist
    })
  },
  tapAdd(e) {
    var index = e.currentTarget.dataset.index
    if (this.data.signlist[index].duration == 30)
      return;
    if (this.data.signlist[index].duration >= 5) {
      this.data.signlist[index].duration += 5;
    } else {
      this.data.signlist[index].duration++
    }
    this.setData({
      signlist: this.data.signlist
    })
  },

  tapMin(e) {
    var index = e.currentTarget.dataset.index
    if (this.data.signlist[index].duration == 1)
      return;
    if (this.data.signlist[index].duration > 5) {
      this.data.signlist[index].duration -= 5;
    } else {
      this.data.signlist[index].duration--
    }
    this.setData({
      signlist: this.data.signlist
    })
  },

  toggle(e) {
    var anmiaton = e.currentTarget.dataset.class;
    var that = this;
    that.setData({
      animation: anmiaton
    })
    setTimeout(function () {
      that.setData({
        animation: ''
      })
    }, 1000)
  },

  async getList() {
    const {
      data: res
    } = await wx.$http.get('/list/get2', {
      uid: this.data.userinfo.uid
    }, {
      token: true,
      checkToken: true
    })
    if (res.code != 200) {
      wx.showToast({
        title: "获取名单失败",
        icon: "none"
      })
    } else {
      if (res.data.list.length == 0) {
        this.locationCancel()
        wx.showModal({
          title: '提示',
          content: '请先去我的新增名单',
          success(res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/teacher/sign_classList',
              })
            } else if (res.cancel) {}
          }
        })
        return
      }
      this.setData({
        classList: res.data.list
      })
      var lists = []
      this.data.classList.forEach(element => {
        lists.push(element.name)
      });
      this.setData({
        lists: lists
      })
      wx.setStorageSync('classList', res.data.list)
    }
  },

  async getTypeList() {
    const {
      data: res
    } = await wx.$http.get('/type/list', {}, {
      token: true,
      checkToken: true
    })
    if (res.code != 200) {
      wx.showToast({
        title: "获取类型名单失败",
        icon: "none"
      })
    } else {
      var types = []
      this.setData({
        typeslist: res.data
      })
      this.data.typeslist.forEach(element => {
        types.push(element.name)
      });
      this.setData({
        types: types
      })
      wx.setStorageSync('typesList', res.data)
    }
  },

  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },

  cancel: function () {
    this.hideModal()
  },

  //改变是否选择定位
  listenerSwitch: function (e) {
    this.setData({
      point: e.detail.value
    })
  },


  // 确定按钮
  onConfirmTap() {},

  // 取消按钮
  onCancelTap() {},

  // 显示 dio
  onShowDioTap() {
    const type = 1;
    const config = JSON.parse(JSON.stringify(this.data.navConfig.config));
    this.setData({
      currentConf: config,
      type
    });
  },


  //改变是否开启名单
  listenerSwitch2: function (e) {
    this.setData({
      listflag: e.detail.value,
      pointflag: [
        false,
        false
      ],
    })
    if (this.data.listflag == false && this.data.firstTip) {
      var navTemp = this.data.navConfig
      navTemp.config.content = "不选择名单，签到结果将不显示未签到成员，且无法开启定位"
      this.setData({
        navConfig: navTemp,
        firstTip: false
      })
      this.onShowDioTap()
    }
  },

  bindScopeChange(e) {
    this.setData({
      scopeIndex: e.detail.value
    })
  },

  chooseLocation: function () {
    // let that = this
    wx.chooseLocation({
      type: 'gcj02',
      success: (res) => {
        this.setData({
          choosen: res,
          flag1: true
        })
      },
    })
  },

  // 新增环节确定按钮
  determine: function () {
    var location_x = 0
    var location_y = 0
    var range = 0
    var whetherLocation=0

    if (this.data.point == true) {
     
      location_x = this.data.choosen.latitude
      location_y = this.data.choosen.longitude
      range = this.data.scopelist[this.data.scopeIndex]
      if (this.data.choosen.latitude == 0 && this.data.choosen.longitude == 0) {
        whetherLocation=1
        wx.showToast({
          title: '请选择位置！',
          icon: 'none'
        })
      } else {
        whetherLocation=1
        this.data.pointflag.push(this.data.point)
        this.setData({
          pointflag: this.data.pointflag
        })
        this.data.signlist.push({
          linkType: Number(this.data.activityIndex) + 1,
          duration: this.data.timelist[this.data.timeIndex],
          startTime: "2020-10-26 14:29:00",
          endTime: "2020-10-26 14:29:00",
          status: 0,
          location_x: location_x,
          location_y: location_y,
          range: range,
          whetherLocation: whetherLocation,
          times: this.data.timeslist[this.data.timesIndex],
        })
        this.setData({
          signlist: this.data.signlist
        })
        this.hideModal()
      }
    } else {
      this.data.pointflag.push(this.data.point)
      this.setData({
        pointflag: this.data.pointflag
      })
      this.data.signlist.push({
        linkType: Number(this.data.activityIndex) + 1,
        duration: this.data.timelist[this.data.timeIndex],
        startTime: "2020-10-26 14:29:00",
        endTime: "2020-10-26 14:29:00",
        status: 0,
        location_x: location_x,
        location_y: location_y,
        range: range,
        whetherLocation: whetherLocation,
        times: this.data.timeslist[this.data.timesIndex],
      })
      this.setData({
        signlist: this.data.signlist
      })
      this.hideModal()
    }
    if (this.data.signlist.length == 2) {
      this.setData({
        hasTwo: true
      })
    }
  },

  delete(e) {
    this.data.pointflag.splice(e.currentTarget.dataset.index, 1)
    this.data.signlist.splice(e.currentTarget.dataset.index, 1)
    this.setData({
      signlist: this.data.signlist,
      pointflag: this.data.pointflag,
      hasTwo: false
    })
  },

  //改变签到类型
  bindTypeChange: function (e) {
    this.setData({
      typeIndex: e.detail.value
    })
  },

  //改变签到方式
  bindTypeChange1: function (e) {
    this.setData({
      typeIndex1: e.detail.value
    })
    // console.log(this.data.typeIndex1)
  },

  //改变名单选择
  bindListChange: function (e) {
    this.setData({
      listIndex: e.detail.value
    })
  },

  locationCancel() {
    var tmp = this.data.pointflag
    tmp[this.data.currentIndex] = !tmp[this.data.currentIndex]
    this.setData({
      pointflag: tmp,
      modalName: null
    })
  },

  //改变签到环节
  bindActivityChange: function (e) {
    this.setData({
      activityIndex: e.detail.value
    })
  },

  bindTimeChange(e) {
    this.setData({
      timeIndex: e.detail.value
    })
  },
  bindTimesChange(e) {
    this.setData({
      timesIndex: e.detail.value
    })
  },
  // 
  async signLaunch(e) {
    var linkType=[]
    var duration=[]
    var whetherLocation=[]
    var rangement=[]
    var times=[]
    var pubdata = this.data.pubdata
    pubdata.id=this.data.id
    pubdata.title = e.detail.value.title
    pubdata.actType = Number(this.data.typeIndex) + 1
    pubdata.caption = e.detail.value.desc
    pubdata.name=e.detail.value.title
    pubdata.useNum=0
    pubdata.cid=''
    pubdata.rangement=0
    pubdata.signStopType=Number(this.data.typeIndex1)
    console.log(this.data.classList[this.data.listIndex]);
    let params = e.detail.value;
    
    if(this.data.pointflag2){
      pubdata.cid = this.data.classList[this.data.listIndex].id || ''
    }
    pubdata.tid = this.data.userinfo.uid

    console.log(this.data.signlist);
    var signlist2=[]
    var durationStr=""
    var linkTypeStr=""
    var timesStr=""
    var whetherLocationStr="0,0"
    for(var i=0;i<this.data.signlist.length;i++){
      for(var j=0;j<this.data.signlist[i].times;j++){
        durationStr=durationStr+Number(this.data.signlist[i].duration)+","
        linkTypeStr=linkTypeStr+this.data.signlist[i].linkType+","
        timesStr=timesStr+Number(this.data.signlist[i].times)+","
        signlist2.push({
          linkType: this.data.signlist[i].linkType,
          duration: Number(this.data.signlist[i].duration),
          startTime: "2020-10-26 14:29:00",
          endTime: "2020-10-26 14:29:00",
          status: 0,
          location_x: this.data.signlist[i].location_x,
          location_y: this.data.signlist[i].location_y,
          range: this.data.signlist[i].range
        })
      }
    }
    // console.log(signlist2)
    // pubdata.listSession =signlist2
    pubdata.duration=durationStr
    pubdata.linkType=linkTypeStr
    pubdata.times=timesStr
    pubdata.whetherLocation=whetherLocationStr
    // pubdata.times=
      if (pubdata.title == ''||this.data.signlist2 == 0) {
      wx.showModal({
        title: '提示',
        content: '请填写完整',
        success(res) {}
      })
      return
    }
    // 将所有的time转换成秒
    console.log(pubdata);
    this.data.pubdata = pubdata
    // wx.User.pubNewAct({
    //   data: pubdata
    // })
    const {
			data: res
    } = await wx.$http.post(`/template/createActivity2?templateId=${this.data.templateId}`,pubdata)
    if (res.code==200) {
      // wx.showToast({
      //   title: 'haha',
      //   icon: 'none'
      // })
      wx.switchTab({
        url: '/pages/teacher/sign_home',
      })
    } 
  },

  __formatPubData(provider, options) {
    return {
      title: provider,
      actType: 0,
      caption: options.authResult.expires_in,
      cid: options.userInfo.nickName,
      tid: this.data.userinfo.uid,
      listSession: options
    }
  },

  __formatListSession(obj) {
    return {
      linkType: obj.linkType,
      duration: this.data.time,
      startTime: obj.startTime,
      endTime: obj.endTime,
      status: obj.status
    }
  },
  getlocation:function(e){
    var that=this
   console.log('dw');
   wx.getLocation({
    type: 'wgs84',
    success (res) {
      const latitude = res.latitude
      const longitude = res.longitude
      const speed = res.speed
      const accuracy = res.accuracy
      console.log(res);
    },
    fail: function (errInfo) {
      console.info(errInfo)
    }
   })
   
    wx.chooseLocation({
      success: function (e) {
        //允许打开定位
        
        console.log("开启了定位",e);
        that.data.choosen.latitude=e.latitude
        that.data.choosen.longitude=e.longitude
        console.log(that.data.choosen);
        that.setData({
          choosen:that.data.choosen
        })
      },
      fail: () => {
        //不允许打开定位
        console.log('fail');
        wx.getSetting({
          success: (res) => {
            if (!res.authSetting['scope.userLocation']) {
              //打开提示框，提示前往设置页面
              that.setData({
                showCon: true
              })
            }
          }
        })
      }
    })
    
  },

})